import { UserAuth } from '../../utils/hooks';
import NotAuth from '../../components/NotAuth';
import React from 'react';
import { Layout, message, List, Button, Row, Col, Progress, Spin } from 'antd';
import { useState, useEffect, useRef } from 'react';
import { useSelector } from 'react-redux';
import { selectUser } from '../../redux/Slice/userSlice';
import { Content, Header } from 'antd/lib/layout/layout';
import { importsExcel } from '../../utils/excel';
import axios from 'axios';
import * as moment from 'moment';
import Config from '../../Config';
import { update } from 'lodash';
const UserBatch = () => {
  const [curCount, SetCount] = useState(0);
  const [loading, SetLoading] = useState(false);
  const [cost, SetCost] = useState(0);
  const [size, Setsize] = useState(0);
  const [UploadData, SetUpdata] = useState([]);
  const [start, SetStart] = useState(Date.now());
  const [errData, SetErr] = useState([]);
  let websocket = null;
  let username = useSelector(selectUser);
  useEffect(() => {
    if ('WebSocket' in window) {
      websocket = new WebSocket('ws://localhost:8080/webSocket/' + username);
      websocket.onopen = event => {};
      websocket.onmessage = event => {
        console.log(event.data);
        let webData = event.data;

        let jsonData = JSON.parse(webData);
        console.log(jsonData);
        console.log(webData);
        // let cur = parseInt(webData);
        SetCount(((jsonData.cur / jsonData.size) * 100).toFixed(2));
        if (jsonData.cur == jsonData.size) {
          let end = Date.now();
          message.success('导入成功,耗时' + (end - start) / 1000 + '秒', 2, () => {
            SetCost((end - start) / 1000);
            SetLoading(false);
          });
        }
        // console.log(((cur + 1) / size) * 100);
      };
    } else {
      message.alert('浏览器不支持websocket,无法使用消息功能');
    }
  });

  return (
    <>
      <Layout>
        <Header
          style={{
            borderRadius: '5px 5px 0px 0px',
            height: '40px',
            padding: '0px 15px',
            margin: '0px 0px',
            backgroundColor: 'white',
            textAlign: 'left',
            lineHeight: '40px',
          }}
        >
          <h3>用户录入</h3>
        </Header>
        <Content style={{ padding: '10px 20px', backgroundColor: 'white' }}>
          <Spin spinning={loading}>
            <Row>
              <Col span={6}>
                {/* <input
                  type="file"
                  accept=".xls,.xlsx"
                  style={{ float: 'left' }}
                  onChange={e => {
                    importsExcel(e).then(
                      function (data) {
                        Setsize(data.length);
                        SetUpdata(data);
                      },
                      function (err) {
                        console.log(err);
                      }
                    );
                  }}
                  
                /> */}
                <input
                  type="file"
                  accept=".xls,.xlsx"
                  style={{ float: 'left' }}
                  onChange={e => {
                    importsExcel(e).then(
                      function (data) {
                        console.log(data);
                        axios
                          .post(Config.baseURL + '/user/excelregister', {
                            excelRegister: data,
                          })
                          .then(res => {
                            if (res.data.code == 1) {
                              message.success('导入成功', 1);
                            } else if (res.data.code >= 10000) {
                              message.error('导入失败');
                            }
                          })
                          .catch(err => {
                            message.error(err, 2);
                          });
                      },
                      function (err) {
                        console.log(err);
                      }
                    );
                  }}
                />
              </Col>
              <Col span={6}>
                <Button
                  onClick={() => {
                    SetLoading(true);
                    SetStart(Date.now());
                    console.log(UploadData);
                    axios
                      .post(Config.baseURL + '/user/excelregister', {
                        excelRegister: UploadData,
                      })
                      .then(res => {
                        console.log(res);
                        if (res.data.code == 1) {
                          // let end = Date.now();
                          // message.success('导入成功,耗时' + (end - start) / 1000 + '秒', 2, () => {
                          //   SetCost((end - start) / 1000);
                          //   SetLoading(false);
                          // });
                        } else {
                          message.error('导入失败' + res.data.message, 2);
                          SetLoading(false);
                        }
                      })
                      .catch(err => {
                        console.log(err);
                        message.error(err, 2);
                        SetLoading(false);
                      });
                  }}
                  type="primary"
                  size="large"
                >
                  上传
                </Button>
              </Col>
              <Col span={2}>
                <Button
                  type="primary"
                  size="large"
                  href="https://instrumentsys.oss-cn-beijing.aliyuncs.com/template/Intemplate.xlsx"
                  target="_blank"
                >
                  下载模板
                </Button>
              </Col>
            </Row>
          </Spin>
          <Row style={{ marginTop: '40px' }}>
            <Col span={12}>
              <Progress
                strokeColor={{
                  '0%': '#108ee9',
                  '100%': '#87d068',
                }}
                percent={curCount}
              />
            </Col>
            <Col span={4}>耗时： {cost} 秒</Col>
          </Row>
          <Row>
            <Row>
              <List
                header="错误信息"
                itemLayout="horizontal"
                dataSource={errData}
                style={{
                  height: '600px',
                  width: '900px',
                  marginTop: '40px',
                }}
                renderItem={item => (
                  <List.Item>
                    <List.Item.Meta
                      title={'错误数据序号： ' + item.cur}
                      description={'错误原因 ' + item.err}
                    />
                  </List.Item>
                )}
              ></List>
            </Row>
          </Row>
        </Content>
      </Layout>
    </>
  );
};

export default () => {
  const { authority } = UserAuth('UserBatch');
  return <>{authority ? <UserBatch /> : <NotAuth />}</>;
};
